package com.qtummatrix.service.servlet;

import com.qtummatrix.dao.UserDao;
import com.qtummatrix.dao.daoImpl.UserDaoImpl;
import com.qtummatrix.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/addUserServlet")
public class AddUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");

        /*//添加用户之前，判断用户上传的图片是否合法
        PrintWriter out = response.getWriter();
        //设置文件上传的大小
        int max = 1024 * 1024 * 5;//5M
        //创建一个磁盘文件工厂类
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建一个解析器
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
        //允许上传的文件类型
        String[] allowExtName = {"jpeg", "jpg", "png", "gif", "bmp", "tga"};
        try {
            List<FileItem> items = servletFileUpload.parseRequest(request);
            for (int i = 0; i < items.size(); i++) {
                FileItem item = items.get(i);
                //判断FileItem对象是否是普通的表单字段
                if (!item.isFormField()) {
                    String contentType = item.getContentType();
                    System.out.println(contentType);//测试
                    ServletContext context = this.getServletContext();
                    String filePath = context.getRealPath("img");//获取文件上传的服务器的物理路径
                    File baseFile = new File(filePath);
                    //判断文件上传路径是否存在,如果不存在没创建一个目录
                    if (!baseFile.exists()) {
                        baseFile.mkdirs();
                    }
                    if (item.getSize() >= max) {
//                        out.println("上传文件大小超出限制");
                        System.out.println("上传文件大小超出限制");
                        return;
                    }

                    //获取上传的文件名称 d:\\ddd\\sss\\image.jpg
                    String fileName = item.getName().substring(item.getName().lastIndexOf("\\") + 1);
                    //	String prefix=fileName.substring(0,fileName.lastIndexOf("."));
                    String lastPrefix = fileName.substring(fileName.lastIndexOf(".") + 1);
                    //	fileName=new String(prefix.getBytes("GBK"),"utf-8")+"."+lastPrefix;
                    int count = 0;
                    for (String filefiex : allowExtName) {
                        if (filefiex.equals(lastPrefix)) {
                            count++;
                            break;
                        }
                    }
                    if (count > 0) {
                        fileName = System.currentTimeMillis() + "." + lastPrefix;
                        File newFile = new File(filePath + "\\" + fileName);
                        item.write(newFile);
                        *//*request.setAttribute("imagePath", "upload\\" + fileName);
                        request.getRequestDispatcher("fileupload.jsp").forward(request, response);*//*
                    } else {
//                        out.println("上传文件类型不合法");
                        System.out.println("上传文件类型不合法");
                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            out.close();
        }*/


        //声明User对象,存储前端传过来的员工数据
        User user = new User();
        UserDao userDao = new UserDaoImpl();

        //**验证输入是否为空将会在最后用前端验证
        String sHeadimg = request.getParameter("sHeadimg");//头像
        String sName = request.getParameter("sName");//姓名
        String sPass = request.getParameter("sPass");//密码
        String sSex = request.getParameter("sSex");//性别
        long sQQ = Long.parseLong(request.getParameter("sQQ"));
        // long sQQ = Long.parseLong(request.getParameter("sQQ"));
        String sEmial = request.getParameter("sEmial");//电子邮箱
        long sTel = Long.parseLong(request.getParameter("sTel"));//电话
        long UId = Long.parseLong(request.getParameter("sUId"));//身份证号
        String sAddress = request.getParameter("sAddress");//住址
        int sPositionId = Integer.parseInt(request.getParameter("sPosition"));//职位Id
        int sDepartment = Integer.parseInt(request.getParameter("sDepartment"));//部门id
        String sPermission = request.getParameter("sPermission");//权限：管理员或者普通用户
        String sMark = request.getParameter("sMark");//备注

        user.setHeadimg(sHeadimg);
        user.setUsername(sName);
        user.setPassword(sPass);
        user.setSex(sSex);
        user.setQq(sQQ);
        user.setEmail(sEmial);
        user.setPhone(sTel);
        user.setUID(UId);
        user.setAddress(sAddress);
        user.setDepartmentId(sDepartment);
        user.setIsAdmin(sPermission);
        user.setPositionId(sPositionId);
        user.setMark(sMark);

        HttpSession session = request.getSession();
        User user1 = (User) session.getAttribute("user");
        int operationUserId = user1.getId();
        int i = userDao.addUser(operationUserId, user);
        if (i > 0) {
            // 注册成功
            request.getRequestDispatcher("/addUser.jsp").forward(request, response);
        } else {
            request.getRequestDispatcher("/errer.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        this.doPost(request, response);
    }
}
